<?php
/**
 * Created by PhpStorm.
 * Script Name: Index.php
 * Create: 2020/11/03 15:23
 * Description: 手机端首页
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\wap\controller;

use app\common\service\Tenant as TenantService;
use plugin\wechat\app\MpController;
use plugin\wechat\app\service\MiniReg as RegService;
use plugin\wechat\app\service\OpenPlatform as OpenPlatformService;

class Index extends MpController
{
    protected $needWxLogin = true;

    public function __construct()
    {
        parent::__construct(); // TODO: Change the autogenerated stub
    }

    /**
     *
     * @return mixed|\support\Response
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function index(){
        $step = input('step', 0);
        $code_types = [
            1 => '统一社会信用代码（18 位）',
            2 => '组织机构代码（9 位 xxxxxxxx-x）',
            3 => '营业执照注册号(15 位)'
        ];
        //return redirect("https://mp.weixin.qq.com/wxawap/fastregistertpbeta?action=create&create_token=UFkoyUwJ7a3AGVeZvuBlagx_QmG0MOVKkcTyXm2Vr8j_bftglcnSooWIZFywA8S7#wechat_redirect");
        $assign = [
            'code_types' => $code_types,
            'step' => $step
        ];
        return $this->show($assign);
    }

    /**
     * 根据昵称注册
     * Author: fudaoji<fdj@kuryun.cn>
     */
    function regPost(){
        $post_data = input('post.');
        $post_data['nick_name'] = ($post_data['name'] ?? '');
        $res = $this->validate($post_data,'\\plugin\\wechat\\app\\validate\\MiniReg.fastReg');
        if($res !== true){
            return $this->error($res, '', ['token' => token()]);
        }
        $params = [
            'name' => $post_data['name'],
            'openid' => $this->followInfo['openid']
        ];
        $res = OpenPlatformService::registerBetaMiniprogram($params);
        if(is_string($res)) {
            return $this->error('微信返回错误：'.$res, '', ['token' => token()]);
        }
        $data = $res['data'];
        $insert = [
            'nick_name' => $post_data['name'],
            'company_id' => $this->mpInfo['company_id'],
            'tenant_id' => $this->tenantId,
            'unique_id' => $data['unique_id'],
            'authorize_url' => $data['authorize_url']
        ];
        RegService::reg($insert);
        return $this->success('注册成功，准备跳转前往授权！', $data['authorize_url'], $post_data);
    }
}